package cn.ccccltd.waf.id_generator.config.redis;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
@Order(-100)
@ConditionalOnProperty(name = "spring.dbtype", havingValue = "redis")
public class RedisConfig {
	
	@Autowired
	RedisProperties redisProperties;
	@Autowired
	JedisPoolProperties jedisPoolProperties;
	
	@Bean
	public RedisConnectionFactory redisFactory() { // 是负责建立Factory的连接工厂类
		
		//redis2.0之后通过这种方式来处理
		RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
		redisStandaloneConfiguration.setHostName(redisProperties.getHost());
		redisStandaloneConfiguration.setPort(redisProperties.getPort());
		redisStandaloneConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
		redisStandaloneConfiguration.setDatabase(redisProperties.getDatabase());
		
		
		//创建jedis连接池
		JedisPoolConfig poolConfig = new JedisPoolConfig(); // 进行连接池配置
		poolConfig.setMaxTotal(jedisPoolProperties.getMaxActive());
		poolConfig.setMaxIdle(jedisPoolProperties.getMaxIdle());
		poolConfig.setMinIdle(jedisPoolProperties.getMinIdle());
		poolConfig.setMaxWaitMillis(jedisPoolProperties.getMaxWait());
		JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder().usePooling().poolConfig(poolConfig).build();
		
		//根据redisStandaloneConfiguration来创建jedis工厂
		JedisConnectionFactory jedisFactory = new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
		
		jedisFactory.afterPropertiesSet();
		
		return jedisFactory;
	}
	
	@Bean
	public RedisTemplate<String, Integer> redisTemplate() {

		RedisTemplate<String, Integer> redisTemplate = new RedisTemplate<String, Integer>();
		
		redisTemplate.setConnectionFactory(redisFactory());
		
		// key的序列化类型
		//redisTemplate.setKeySerializer(new StringRedisSerializer());
		// value的序列化类型
		//redisTemplate.setValueSerializer(new RedisObjectSerializer());
		
		return redisTemplate;
		
	}
	
	@PostConstruct
	public void init() {
		
		System.err.println("开始初始化redis");
		
	}
}
